package com.szgd.util;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpUtils {
    private static String USER_AGENT = "Mozilla/5.0";
    private static Logger logger = Logger.getLogger(HttpUtils.class);
    public static final String CHARSET = "UTF-8";
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlName = "";
            if (param.length() != 0) {
                urlName = url + "?" + param;
            } else
                urlName = url;
            URL resUrl = new URL(urlName);
            URLConnection urlConnec = resUrl.openConnection();
            urlConnec.setRequestProperty("accept", "*/*");
            urlConnec.setRequestProperty("connection", "Keep-Alive");
            urlConnec.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            urlConnec.connect();
            Map<String, List<String>> map = urlConnec.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(urlConnec.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送get请求失败" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }



    //post请求方法
    public static  String sendPost(String url, Map<String,Object> params,String contentType) {
        String response = "";
        System.out.println(url);
        try {
            List<BasicNameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);

                // StringEntity stringentity = new StringEntity(data);
                if (pairs != null && pairs.size() > 0) {
                    httppost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
                }
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils.toString(httpresponse.getEntity());
                System.out.println(response);
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public static  byte[] downLoadJpgFromOtherSystem(String sUrl) {
        ByteArrayOutputStream output = null;
        String total = "";
        String line;
        try {
            URL url = new URL(sUrl);
            URLConnection urlc = url.openConnection();
            InputStream is = urlc.getInputStream(); // To download
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = is.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                }
            }
        }
        return null;
    }
    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) throws Exception {

        String url = "http://61.155.204.87:8888/login.jsp";
        String imgUrl = "http://61.155.204.87:8888/jsp/ValidateCodeServlet";
        String loginUrl = "http://61.155.204.87:8888/login.do?method=loginRisk&t="+Math.random();
        //String code = OcrUtil.ocrImage(HttpUtils.downLoadJpgFromOtherSystem(imgUrl));
        //String code = OcrUtil.getCode(HttpUtils.downLoadJpgFromOtherSystem(imgUrl));
        String code = "";
        String username= "chenhaifeng";
        String password= "suzhou123";
        String address = "(IP：218.80.193.33；位置：上海市浦东新区)";
        CloseableHttpClient httpclient = HttpClients.createDefault();

        //设置登录参数
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("name", username));
        formparams.add(new BasicNameValuePair("password", password));
        formparams.add(new BasicNameValuePair("image", code));
        formparams.add(new BasicNameValuePair("address", address));
        UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");

        //新建Http  post请求
        HttpPost httppost = new HttpPost(loginUrl);
        httppost.setEntity(entity1);
        httppost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
        httppost.setHeader("Accept-Encoding","gzip, deflate");
        httppost.setHeader("Accept-Language","zh-CN,zh;q=0.9");
        httppost.setHeader("Host","61.155.204.87:8888");
        httppost.setHeader("Upgrade-Insecure-Requests","1");
        httppost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36");
        //处理请求，得到响应
        HttpResponse response = httpclient.execute(httppost);

        String set_cookie = response.getFirstHeader("Set-Cookie").getValue();

        //打印Cookie值
        System.out.println(set_cookie.substring(0,set_cookie.indexOf(";")));

        //打印返回的结果
        HttpEntity entity = response.getEntity();

        StringBuilder result = new StringBuilder();
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(instream));
            String temp = "";
            while ((temp = br.readLine()) != null) {
                String str = new String(temp.getBytes(), "utf-8");
                result.append(str);
            }
        }
        System.out.println("session："+result);
        System.out.println("结果---");
        
        
        String jcsjUrl = "http://61.155.204.87:8888/monitorData.do?method=showMonitorData&user_type=1&location_id=230";
        HttpPost httppost2 = new HttpPost(jcsjUrl);
        HttpResponse response2 = httpclient.execute(httppost2);

    }

}
